//
//  GMAddClientViewController.m
//  GuardMan
//
//  Created by steven on 2017/2/24.
//  Copyright © 2017年 steven. All rights reserved.
//

#import "GMAddClientViewController.h"
#import "GMButton.h"
#import "GMGuardModel.h"
#import "GMQrCodeView.h"
#import "GMAddClientDataController.h"
#import "NSDate+Utils.h"
#import <MBProgressHUD/MBProgressHUD.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import <MSWeakTimer/MSWeakTimer.h>

@interface GMAddClientViewController ()

@property (nonatomic, strong)GMQrCodeView *qrCodeView;
@property (nonatomic, strong)GMButton *confirmButton;
@property (nonatomic, strong) UIImageView *okImageView;

@property (nonatomic, strong)GMAddClientDataController *clientDataController;
@property (nonatomic, strong)GMGuardModel *guardModel;

@property (nonatomic, strong)MSWeakTimer *timer;
@property (nonatomic, assign)BOOL isFinished;
@end

@implementation GMAddClientViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.clientDataController = [[GMAddClientDataController alloc] init];
    self.guardModel = [[GMGuardModel alloc] init];
    // Flag to show if end success
    self.isFinished = NO;

    [self initializeForm];
    [self setupMainView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [self beginGuard];
}

- (void)viewWillDisappear:(BOOL)animated {
    if (!self.isFinished && [self.navigationController.childViewControllers indexOfObject:self] == NSNotFound) {
        [self endGuardWithOption:@"cancel"];
    }

    [super viewWillDisappear:animated];
}

#pragma mark - setup mainview
- (void)setupMainView {
    self.navigationItem.title = @"添加客户";

    self.view.backgroundColor = [UIColor whiteColor];
    
    // confirm button
    [self.view addSubview:self.confirmButton];
    [self.confirmButton autoAlignAxisToSuperviewAxis:ALAxisVertical];
    [self.confirmButton autoSetDimensionsToSize:CGSizeMake(184, 44)];
    [self.confirmButton autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:20];
    
    // table view
    [self.view addSubview:self.tableView];
    [self.tableView autoPinEdgeToSuperviewEdge:ALEdgeTop];
    [self.tableView autoPinEdge:ALEdgeBottom toEdge:ALEdgeTop ofView:self.confirmButton];
    [self.tableView autoPinEdgeToSuperviewEdge:ALEdgeLeading];
    [self.tableView autoPinEdgeToSuperviewEdge:ALEdgeTrailing];

    self.tableView.tableHeaderView = self.qrCodeView;
    self.tableView.backgroundColor = [UIColor whiteColor];
}

- (void)initializeForm {
    XLFormRowDescriptor *row;
    XLFormSectionDescriptor * section;

    XLFormDescriptor *form = [XLFormDescriptor formDescriptor];

    // First section
    section = [XLFormSectionDescriptor formSection];
    [form addFormSection:section];

    // username
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"name" rowType:XLFormRowDescriptorTypeText title:@"姓名"];
    row.cellConfig[@"textField.textColor"] = [UIColor grayColor];
    row.cellConfig[@"textField.textAlignment"] = @(NSTextAlignmentRight);
    row.disabled = @YES;
    [section addFormRow:row];

    // phone
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"phone" rowType:XLFormRowDescriptorTypeText title:@"手机号"];
    row.cellConfig[@"textField.textColor"] = [UIColor grayColor];
    row.cellConfig[@"textField.textAlignment"] = @(NSTextAlignmentRight);
    row.disabled = @YES;
    [section addFormRow:row];

    // guard sn
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"endTime" rowType:XLFormRowDescriptorTypeDate title:@"还款日期"];
    row.value = [NSDate dateWithTimeIntervalSinceNow:0];
    [section addFormRow:row];

    self.form = form;
}

#pragma mark - check guard
- (void)checkGuard {
    NSDictionary *params = @{@"sn": self.guardModel.sn};
    __weak typeof(self)weakSelf = self;
    [self.clientDataController checkGuardWithParams:params callback:^(NSString *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;
        if (error == nil) {
            [strongSelf renderCheckSuccessView];
        } else {
            [strongSelf showAlertMessage:error];
        }
    }];
}

#pragma mark - begin guard
- (void)beginGuard {
    [self.clientDataController beginGuardWithParams:nil callback:^(NSString *error) {
        if (error == nil) {
            [self renderSuccessView];
        } else {
            [self showAlertMessage:error];
        }
    }];
}

#pragma mark - end guard
- (void)endGuardWithOption:(NSString *)option {
    NSDictionary *formDict = [self.form formValues];

    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    params[@"guardId"] = [NSString stringWithFormat:@"%ld", (long)self.guardModel.id];
    params[@"confirm"] = option;
    if ([option isEqualToString:@"ok"]) {
        params[@"end_time"] = [NSDate stringFromDate: formDict[@"endTime"]];
    }
    [self.clientDataController endGuardWithParams:params callback:^(NSString *error) {
        if ([option isEqualToString:@"ok"]){
            if (error == nil) {
                [self renderConfirmSuccessView];
            } else {
                [self showAlertMessage:error];
            }
        } else {
            if (error == nil) {
                NSLog(@"取消守卫成功!");
            } else {
                NSLog(@"%@", error);
            }
        }
    }];
}

#pragma mark - check guard status ok
- (void)renderCheckSuccessView {
    NSDictionary *checkDict = self.clientDataController.checkResult;
    NSLog(@"===> check status: %@", checkDict[@"status"]);

    if ([checkDict[@"status"] isEqualToString:@"on"]) {
        // Stop timer
        [self.timer invalidate];
        self.timer = nil;
    
        // enable confirm button
        self.confirmButton.enabled = YES;
        
        // show what we got
        UIImageView *okImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ok-icon"]];
        UIImageView *okImageView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ok-icon"]];
        
        [self.form formRowWithTag:@"name"].cellConfig[@"accessoryView"] = okImageView;
        [self.form formRowWithTag:@"phone"].cellConfig[@"accessoryView"] = okImageView2;
        [self.form formRowWithTag:@"name"].value = checkDict[@"name"];
        [self.form formRowWithTag:@"phone"].value = checkDict[@"phone_number"];
        
        [self.tableView reloadData];
    }
}

#pragma mark - get guard success
- (void)renderSuccessView {
    self.guardModel = self.clientDataController.guardModel;
    NSString *qrCodeUrl = self.guardModel.qrCodeUrl;
    [self.qrCodeView.qrImageView sd_setImageWithURL:[[NSURL alloc] initWithString:qrCodeUrl]];

    // Check guard form now on
    self.timer = [MSWeakTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkGuard) userInfo:nil repeats:YES dispatchQueue:dispatch_get_main_queue()];
}

#pragma mark - confirm guard
- (void)renderConfirmSuccessView {

    self.isFinished = YES;

    [self showAlertMessage:@"添加守卫成功"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.navigationController popViewControllerAnimated:YES];
    });
}

- (GMQrCodeView *)qrCodeView {
    if (!_qrCodeView) {
        _qrCodeView = [[GMQrCodeView alloc] init];
    }
    return _qrCodeView;
}

#pragma mark - confirm button
- (GMButton *)confirmButton {
    if (!_confirmButton) {
        _confirmButton = [[GMButton alloc] init];
        [_confirmButton addTarget:self action:@selector(confirmButtonPressed) forControlEvents:UIControlEventTouchUpInside];
        [_confirmButton setTitle:@"确认无误，OK" forState:UIControlStateNormal];
        _confirmButton.enabled = NO;
    }
    
    return _confirmButton;
}

- (UIImageView *)okImageView {
    if (!_okImageView) {
        _okImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ok-icon"]];
    }

    return _okImageView;
}

#pragma mark - confirm
- (void)confirmButtonPressed {
    [self endGuardWithOption:@"ok"];
}

#pragma mark - UITableViewDatasource
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return self.view.bounds.size.width-20;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - show alert message
- (void)showAlertMessage:(NSString *)msg {
    dispatch_async(dispatch_get_main_queue(), ^{
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = msg;
        // Configure for text only and offset down
        hud.margin = 10.f;
        hud.yOffset = Main_Screen_Height/2-98;
        hud.removeFromSuperViewOnHide = YES;

        [hud hide:YES afterDelay:MESSAGE_SHOW_TIME];
    });
}

@end
